import { DependencyList, useRef } from "react"

/**
 * 判断依赖数组是否相同
 * @param oldDeps 旧的依赖数组
 * @param deps 新的依赖数组
 */
const depsAreSame = (
  oldDeps: DependencyList,
  deps: DependencyList
): boolean => {
  if (oldDeps === deps) return true

  for (let i = 0; i < oldDeps.length; i++) {
    if (!Object.is(oldDeps[i], deps[i])) return false
  }

  return true
}

/**
 * 强化 useMemo 或 useRef
 * @param fn 函数
 * @param deps 依赖项
 * @returns
 */
const useCreation = <T>(fn: () => T, deps: DependencyList) => {
  const { current } = useRef({
    deps,
    obj: undefined as T | undefined,
    initialized: false,
  })

  if (current.initialized === false || !depsAreSame(current.deps, deps)) {
    current.obj = fn()
    current.deps = deps
    current.initialized = true
  }

  return current.obj as T
}

export default useCreation
